home *** CD-ROM | disk | FTP | other *** search
/ Almathera Ten Pack 3: CDPD 3 / Almathera Ten on Ten - Disc 3: CDPD3.iso / fish / 001-100 / 001-025 / 018 / xlisp1.6 / queens.lsp < prev    next >
Lisp/Scheme  |  1995-03-17  |  1KB  |  49 lines

  1. ;
  2. ; Place n queens on a board
  3. ;  See Winston and Horn Ch. 11
  4. ; Usage:
  5. ;    (queens <n>)
  6. ;          where <n> is an integer -- the size of the board - try (queens 4)
  7.  
  8. (defun cadar (x)
  9.   (car (cdr (car x))))
  10.  
  11. ; Do two queens threaten each other ?
  12. (defun threat (i j a b)
  13.   (or (equal i a)            ;Same row
  14.       (equal j b)            ;Same column
  15.       (equal (- i j) (- a b))        ;One diag.
  16.       (equal (+ i j) (+ a b))))        ;the other diagonal
  17.  
  18. ; Is poistion (n,m) on the board safe for a queen ?
  19. (defun conflict (n m board)
  20.   (cond ((null board) nil)
  21.     ((threat n m (caar board) (cadar board)) t)
  22.     (t (conflict n m (cdr board)))))
  23.  
  24.  
  25. ; Place queens on a board of size SIZE
  26. (defun queens (size)
  27.   (prog (n m board)
  28.     (setq board nil)
  29.     (setq n 1)            ;Try the first row
  30.     loop-n
  31.     (setq m 1)            ;Column 1
  32.     loop-m
  33.     (cond ((conflict n m board) (go un-do-m))) ;Check for conflict
  34.     (setq board (cons (list n m) board))       ; Add queen to board
  35.     (cond ((> (setq n (1+ n)) size)            ; Placed N queens ?
  36.            (print (reverse board))))           ; Print config
  37.     (go loop-n)                       ; Next row which column?
  38.     un-do-n
  39.     (cond ((null board) (return 'Done))        ; Tried all possibilities
  40.           (t (setq m (cadar board))           ; No, Undo last queen placed
  41.          (setq n (caar board))
  42.          (setq board (cdr board))))
  43.  
  44.     un-do-m
  45.     (cond ((> (setq m (1+ m)) size)          ; Go try next column
  46.            (go un-do-n))
  47.           (t (go loop-m)))))
  48.